package com.example.mydemo.controller;

import com.google.code.kaptcha.Producer;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;


    @RestController
    public class CaptchaController {
        @Autowired
        private Producer kaptchaProducer;

        @GetMapping("/captcha")
        public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
            String text = kaptchaProducer.createText();
            BufferedImage image = kaptchaProducer.createImage(text);

            System.out.println("验证码：" + text);

            // 把验证码存到session
            session.setAttribute("captcha", text);

            // 输出图片流
            response.setContentType("image/jpeg");
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
            out.flush();
            out.close();
        }
    }
